package edu.hcmus.sow.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import edu.hcmus.sow.domain.security.CustomUser;

public class SecurityUtil {
   public static final String NONE = "N";
   public static final String HIDDEN = "H";
   public static final String READ = "R";
   public static final String FULL = "F";

   public static Integer getCurrentClient() {
      CustomUser user = (CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      // get current client id by sub domain
      return user.getClientID();
   }

   public static Integer getCurrentLoggedinUserID() {
      CustomUser user = (CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      // get logged in user id
      return user.getUserID();
   }

   public static String getCurrentLoggedinUsername() {
      CustomUser user = (CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      // get logged in user name
      return user.getUsername();
   }

   public static CustomUser getLoggedinUser() {
      CustomUser user = (CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      return user;
   }

   public static boolean isAdmin() {
      CustomUser user = (CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      Set<GrantedAuthority> dbAuthsSet = (Set<GrantedAuthority>) user.getAuthorities();
      List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthsSet);
      GrantedAuthority admin = new SimpleGrantedAuthority("ROLE_ADMINISTRATOR");
      for (GrantedAuthority auth : dbAuths) {
         if (((SimpleGrantedAuthority) auth).equals(admin))
            return true;
      }
      return false;
   }
}
